/*
 * Copyright Eduardo Aponte 2013
 * aponteeduardo@gmail.com
 */
#include <eyelink.h>
#include "mex.h"
#include "utils.h"



INT16 _main( ELINKADDR node, INT16 bt )
{
    return eyelink_open_node( node, bt );     
}


void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
    mwSize td[2] = {1,1};
    double *status;
    int i;
    /* Busy test */
    int bt;
    /* Buffer size */
    int bs; 
    /* Matlab buffer: WARNING no protection against buffer over load */
    char *mb;
    /* Eyelink char. To support compatibility.*/
    ELINKADDR elb;
    
    
    /* Verify input arguments. */
    if(nrhs != 2 ) {
        mexErrMsgTxt("Incorrect number of inputs.");
    } else if( nlhs > 1 ) {
        mexErrMsgTxt("Too many output arguments.");
    }
    
    
    if ( mxIsChar(*prhs) != 1 )
      mexErrMsgTxt( "node must be a string.");
      
    mb  = mxArrayToString(*prhs);
    
    if(mb == NULL) 
      mexErrMsgTxt("Could not convert input to string.");
    
    bs  = (mxGetM(*prhs) * mxGetN(*prhs));
    if(bs != ELINKADDRSIZE)
        mexErrMsgTxt("node should be exactly 16 characters.");

    for (i = 0; i < ELINKADDRSIZE; i++)
        elb[i] = (byte ) mb[i];
 
    if ( isscalar( prhs[1] ) ){
        INT16 scalar;
        /* Returns the scalar, casts to int if necessary. Returns 0 if */
        /* input is complex. */
        if ( returnscalar( prhs[1], &bt ) != 1 )
        mexErrMsgTxt("Complex data is not supported.");                        
    } else {
        mexErrMsgTxt("busytest should be a scalar."); 
    }   
    
    plhs[0] = mxCreateNumericArray( 2, td, mxDOUBLE_CLASS, mxREAL);
    status = mxGetPr(plhs[0]);
    *status = (double ) _main( elb, (INT16 ) bt );
    return;
}


